// pages/hotel/detail.js
var WxParse = require('../../wxParse/wxParse.js');
import {
    hotel,
    user,
    marketing,
    wxapp
} from '../../api/apiData'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        bannerList: [{
            path: '/images/banner.png',
            url: ''
        }],
        status: false,
        info: '',
        distance_new: '',
        hotel_id: '',
        roomList: [],
        show: false,
        date: '',
        startDate: '',
        endDate: '',
        endWeek: '',
        startWeek: '',
        dayNum: 1,
        checkin_date: '',
        checkout_date: '',
        showNum: false,
        room_quantity: 1,
        contact_name: '',
        contact_phone: '',
        note: '',
        has_collect: 0,
        maxDate: '',
        list: [],
        showCoupon: false,
        listCou: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        that.setData({
            hotel_id: options.id
        })
        this.getList()

    },
    toShowCou() {
        this.setData({
            showCoupon: true
        })
    },
    onCloseCou() {
        this.setData({
            showCoupon: false
        })
    },
    toPre(e) {
        let imgs = e.currentTarget.dataset.imgs
        let index = e.currentTarget.dataset.index
        wx.previewImage({
            urls: imgs,
            current: index
        })
    },
    getList() {
        marketing.coupon.lists({
            use_scene: 2,
            merchant_id: this.data.hotel_id
        }, res => {
            if (res.code == 1) {
                this.setData({
                    listCou: res.data
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                })
            }
        })
    },
    toReceive(e) {
        let id = e.currentTarget.dataset.id
        marketing.coupon.receive({
            coupon_id: id
        }, res => {
            if (res.code == 1) {
                wx.showToast({
                    title: res.msg
                })
                setTimeout(() => {
                    this.getList()
                }, 1000)
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                })
            }
        })
    },
    // 收藏
    toCollect() {
        user.collect.submit({
            module: 'hotel',
            module_id: this.data.info.id
        }, res => {
            if (res.code == 1) {
                wx.showToast({
                    title: res.data.message,
                })
                let has_collect = this.data.has_collect == 0 ? 1 : 0
                this.setData({
                    has_collect
                })
            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                })
            }
        })
    },
    onChange(e) {
        this.setData({
            room_quantity: e.detail
        })
    },

    toCancel() {
        this.setData({
            showNum: false
        })
    },
    toShow() {
        this.setData({
            showNum: true
        })
    },
    // 获取详情
    getDetail() {
        let that = this
        hotel.detail({
            hotel_id: this.data.hotel_id
        }, res => {
            this.setData({
                info: res.data,
                has_collect: res.data.has_collect
            })
            if (res.data.max_order_days != 0) {
                const timestamp = new Date(new Date().setDate(new Date().getDate() + 90)).getTime();
                this.setData({
                    maxDate: timestamp
                })
            }

            WxParse.wxParse('bindName', 'html', res.data.intro_content, this, 5)

            wx.getLocation({
                type: 'wgs84',
                success: function (re) {
                    let distance_new = that.distance(re.latitude, re.longitude, res.data.latitude, res.data.longitude)
                    that.setData({
                        distance_new: distance_new
                    })
                }
            })
        })
    },
    // 获取今日
    getNowDay() {
        // 创建一个Date对象
        const today = new Date();
        this.setData({
            startWeek: this.getWeekdayName(today),
            endWeek: this.getWeekdayName2(today),
            startDate: this.formatDate(today),
            endDate: this.getNextDate(),
            checkin_date: this.formatDate2(today),
            checkout_date: this.getNextDate2()
        })
    },
    toOrder(e) {
        let id = e.currentTarget.dataset.id
        let obj = {
            type_id: id,
            checkin_date: this.data.checkin_date,
            checkout_date: this.data.checkout_date,
            // room_quantity:this.data.room_quantity,
            dayNum: this.data.dayNum
        }
        wx.navigateTo({
            url: '/pages/hotel/order?obj=' + JSON.stringify(obj),
        })
    },
    onDisplay() {
        this.setData({
            show: true
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    getNextDate() {
        var now = new Date();
        var date = now.getDate();
        now.setDate(date + 1); //获取后一天
        // now.setDate(date - 1);  //获取前一天
        var y = now.getFullYear();
        var m = (now.getMonth() + 1).toString().padStart(2, "0");
        var d = now.getDate().toString().padStart(2, "0");
        return m + "月" + d + '日';
    },
    getNextDate2() {
        var now = new Date();
        var date = now.getDate();
        now.setDate(date + 1); //获取后一天
        // now.setDate(date - 1);  //获取前一天
        var y = now.getFullYear();
        var m = (now.getMonth() + 1).toString().padStart(2, "0");
        var d = now.getDate().toString().padStart(2, "0");
        return y + '-' + m + "-" + d;
    },
    formatDate(date) {
        date = new Date(date);
        return `${(date.getMonth() + 1).toString().padStart(2, "0")}月${date.getDate().toString().padStart(2, "0")}日`;
    },
    formatDate2(date) {
        date = new Date(date);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },
    onConfirm(event) {
        console.log(event)
        const [start, end] = event.detail;
        let startDate = this.formatDate(start)
        let endDate = this.formatDate(end)
        let startWeek = this.getWeekdayName(start)
        let endWeek = this.getWeekdayName(end)
        console.log(this.getWeekdayName(start))
        let dayNum = this.calculateDaysDifference(start, end)
        this.setData({
            show: false,
            startDate: startDate,
            endDate: endDate,
            startWeek,
            endWeek,
            dayNum,
            checkin_date: this.formatDate2(start),
            checkout_date: this.formatDate2(end)
        });
        this.getRoomList()
    },
    getWeekdayName(date) {
        const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        return weekdays[date.getDay()];
    },
    getWeekdayName2(date) {
        const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
        return weekdays[date.getDay() + 1];
    },
    // 计算相差几天
    calculateDaysDifference(date1, date2) {
        // 将日期字符串转换为Date对象
        const d1 = new Date(date1);
        const d2 = new Date(date2);

        // 获取两个日期的时间戳（毫秒数）
        const timeDiff = Math.abs(d2.getTime() - d1.getTime());

        // 将时间戳转换为天数（1000毫秒 * 60秒 * 60分钟 * 24小时）
        const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

        return diffDays;
    },
    getRoomList() {
        hotel.room.lists({
            hotel_id: this.data.hotel_id,
            checkin_date: this.data.checkin_date,
            checkout_date: this.data.checkout_date
        }, res => {
            if (res.code == 1) {
                this.setData({
                    roomList: res.data
                })

            } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'error'
                })
            }
        })
    },
    toMap() {
        let infos = this.data.info
        let latitude = Number(infos.latitude)
        let longitude = Number(infos.longitude)
        wx.getLocation({
            type: 'wgs84',
            success: function (res) {
                wx.openLocation({ //​使用微信内置地图查看位置。
                    latitude: latitude, //要去的纬度-地址
                    longitude: longitude, //要去的经度-地址
                    name: infos.name,
                    address: infos.address
                })
            },
            fail(res) {
                console.log(res)
            }
        })
    },
    toCall() {
        let infos = this.data.info
        wx.makePhoneCall({
            phoneNumber: infos.telephone,
        })
    },
    distance(la1, lo1, la2, lo2) {
        var La1 = (la1 * Math.PI) / 180.0
        var La2 = (la2 * Math.PI) / 180.0
        var La3 = La1 - La2
        var Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0
        var s =
            2 *
            Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(La3 / 2), 2) +
                    Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)
                )
            )
        s = s * 6378.137
        s = Math.round(s * 10000) / 10000
        s = s.toFixed(2)
        return s
    },
    toUrl(e) {
        let url = e.currentTarget.dataset.url
        wx.navigateTo({
            url: url,
        })
    },
    tozhe() {
        this.setData({
            status: true
        })
    },
    tozhe2() {
        this.setData({
            status: false
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this
        that.getInfo()
        that.getNowDay()
        that.getDetail()
        that.getRoomList()
        hotel.comment.lists({
            hotel_id: that.data.hotel_id,
            page: 1,
            size: 5
        }, res => {
            if (res.code == 1) {
                this.setData({
                    list: res.data.list
                })
            }
        })
    },
    getInfo() {
        let token = wx.getStorageSync('token')
        if (token) {
            // 获取用户详情
            user.detailS({}, res => {
                if (res.code == 20003) {
                    this.getUserInfos()
                } else {

                }

            })
        } else {
            this.getUserInfos()

        }
    },
    /**
     * 授权登录
     */
    getUserInfos(e) {
        let that = this
        wx.login({
            success(res) {
                console.log(res)
                let code = res.code
                wx.getUserInfo({
                    success: (res) => {
                        var encryptedData = res.encryptedData;
                        var iv = res.iv
                        var info = res.rawData
                        var obj = {
                            code: code,
                            iv: iv,
                            encryptedData: encryptedData
                        }
                        wxapp.login(obj, res => {
                            if (res.code == 1) {
                                wx.setStorage({
                                    key: "token",
                                    data: res.data.token
                                })
                                that.getDetail()
                            } else {
                                wx.showToast({
                                    title: res.msg,
                                    icon: 'none'
                                })
                            }
                        })
                    },
                    fail: res => {

                    }
                })
            }
        })
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})